package com.lnsoft.dqfs.server.util;

import io.netty.buffer.ByteBuf;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lnsoft.dqfs.server.dao.Yc;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class DeCrypt {
	private static final Logger log = LoggerFactory.getLogger(DeCrypt.class);
    private Cipher cipher = null;
    
    //	实例构造方法：初始化解密相关工作
    public DeCrypt() {
    	try {
    	    //  初始化解密
            cipher = Cipher.getInstance("AES/ECB/NoPadding");
            //  密码
            byte[] secKey = "wwwlinkotechcom.".getBytes();
            SecretKeySpec secretKeySpec = new SecretKeySpec(secKey, "AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
    	} catch (Exception e) {
            e.printStackTrace();
		}
    }
    
    //	解密字节流，返回Yc实体类(Yc为腐蚀量信息的实体类)
    public List<Yc> encryptedBytes2YcList(int clientName,ByteBuf byteBuf){
    	List<Yc> list = new ArrayList<Yc>();
    	int writerIndex = byteBuf.writerIndex();
        int readerIndex = byteBuf.readerIndex();
        int len = writerIndex - readerIndex;
        int group = len / 320;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        try {
        	for (int i = 0; i < group; i++) {
                //  进行解密
                    byte[] firstArray = new byte[176];
                    byteBuf.readBytes(firstArray);
                    log.info("客户端{}:2504，加密的字节:{}", clientName, Arrays16.toString(firstArray));
                    byte[] original1 = cipher.doFinal(firstArray);
                    log.info("客户端{}:2504，被解密的字节:{}", clientName, Arrays16.toString(original1));
                    String strOriginal1 = new String(original1, "utf-8");
                    log.info("客户端{}:2504，被解密的字符串:{}", clientName, strOriginal1);

                    byte[] secondArray = new byte[144];
                    byteBuf.readBytes(secondArray);
                    log.info("客户端{}:2504，加密的字节:{}", clientName, Arrays16.toString(secondArray));
                    byte[] original2 = cipher.doFinal(secondArray);
                    log.info("客户端{}:2504，被解密的字节:{}", clientName, Arrays16.toString(original2));
                    String strOriginal2 = new String(original2, "utf-8");
                    log.info("客户端{}:2504，被解密的字符串:{}", clientName, strOriginal2);

                    String line = new StringBuilder().append(strOriginal1).append(strOriginal2).toString();
                    
                    //  检查读取的一行数据
                    if (line == null || !line.startsWith("16")) {
                        log.debug("客户端{}:{}，文件数据行异常:文件行为null或者不是‘16’开头", clientName);
                        continue;
                    }


                    line = line.replace("\n", "").trim();

                    if (line.lastIndexOf("16,2") > 1) {
                        line = line.substring(line.lastIndexOf("16,2"));
                    }

                    String[] datas = line.split(",");

                    //  检查数据完整性，一组数据应该是34个字段
                    if (datas.length != 34) {
                        continue;
                    }

                    Yc yc = new Yc();
                	yc.setCjsj(sdf.format(sdf2.parse(datas[1])));
                	yc.setTyndy(MessageUtil.upNanVal(datas[3].trim()));
                	yc.setDcdy(MessageUtil.upNanVal(datas[5].trim()));
                	yc.setJxwd(MessageUtil.upNanVal(datas[7].trim()));
                	yc.setJxsd(MessageUtil.upNanVal(datas[9].trim()));
                	yc.setGprs(MessageUtil.upNanVal(datas[11].trim()));
                	yc.setHjwd(MessageUtil.upNanVal(datas[13].trim()));
                	yc.setHjsd(MessageUtil.upNanVal(datas[15].trim()));
                	yc.setSond(MessageUtil.upNanVal(datas[17].trim()));
                	yc.setYf(MessageUtil.upNanVal(datas[19].trim()));
                	yc.setBy1(MessageUtil.upNanVal(datas[21].trim()));
                	yc.setBy2(MessageUtil.upNanVal(datas[23].trim()));
                	yc.setBy3(MessageUtil.upNanVal(datas[25].trim()));
                	yc.setZndl(MessageUtil.upNanVal(datas[27].trim()));
                	yc.setCudl(MessageUtil.upNanVal(datas[29].trim()));
                	yc.setAldl(MessageUtil.upNanVal(datas[31].trim()));
                	yc.setFedl(MessageUtil.upNanVal(datas[33].trim()));
                    
                    list.add(yc);
                }
        } catch (Exception e) {
			// TODO: handle exception
        	e.printStackTrace();
		}
    	
    	return list;
    }

}
